package com.circle.search;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;

import com.circle.search.model.EsResult;

public class EsSearch {
	public final static String clusterHosts="10.10.76.176,10.10.76.177,10.10.76.178";
	
	public static EsResult searchEsByPassport(String passport, TransportClient client){
		EsResult esResult = new EsResult();
		String[] hostslist = clusterHosts.split(",");
		for (String h : hostslist) {
			client.addTransportAddress(new InetSocketTransportAddress(h, 9300));
		}
		QueryBuilder urlQuery = QueryBuilders.termQuery("passport", passport);
		SearchResponse searchResponse = client.prepareSearch("movieuc_filter_2016-12-07").setTypes("movieuc_filter")
				.setQuery(urlQuery).setSize(100).execute().actionGet();
		SearchHits searchHits = searchResponse.getHits();
		Set<String> uidSet = new HashSet<String>();  
		for (SearchHit searchHit : searchHits) {
			String uid = (String) searchHit.getSource().get("uid");
			uidSet.add(uid);
		}
		System.out.println(uidSet.size());
		esResult.setUid(StringUtils.join(uidSet.toArray(), ","));
		esResult.setUidCount((int)searchHits.getTotalHits());
		return esResult;
	}
}
